import { Injectable, inject } from '@angular/core';
import { JiupianService } from './jiupian.service';
import { ElectronService } from '@/service/electron.service';


@Injectable({
    providedIn: 'root'
})
export class MapApiService {
    jiupianService = inject(JiupianService);
    electronService = inject(ElectronService);

    baidu_ak = 'QHCjD8WUhDsXg5uZBRAL0MEAPpko0u9u';

    async get_location_from_address(address: string) {
        const url = `https://api.map.baidu.com/geocoding/v3/?address=${address}&output=json&ret_coordtype=gcj02ll&ak=${this.baidu_ak}`;

        try {
            const response = await fetch(url);
            const location = await response.json();
            const gcj_lon = location.result.location.lng;
            const gcj_lat = location.result.location.lat;

            return this.jiupianService.gcj02_to_wgs84(gcj_lon, gcj_lat);
        } catch (err) {
            return null;
        }
    }

    async get_address_from_location(lon: number, lat: number) {
        const {gcj_lon, gcj_lat} =  this.jiupianService.wgs84_to_gcj02(lon, lat);
        const url = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${this.baidu_ak}&extensions_poi=1&entire_poi=1&sort_strategy=distance&output=json&coordtype=gcj02ll&location=${gcj_lat}, ${gcj_lon}`;

        try {
            const response = await fetch(url);
            const result = await response.json();
            let address = result.result.formatted_address;
            if (!!address) {
                if(!!result.result.sematic_description) {
                    address += ('; ' + result.result.sematic_description);
                }                
            } else {
                if(!!result.result.sematic_description) {
                    address = result.result.sematic_description;
                } else {
                    address = '未命名';
                }
            }
            return address;
        } catch (err) {
            return '未命名';
        }
    }

    async get_drive_route(orig: any, dest: any, style: number) {
        const url = `https://api.tianditu.gov.cn/drive?postStr={"orig":"${orig.lon.toFixed(6)},${orig.lat.toFixed(6)}","dest":"${dest.lon.toFixed(6)},${dest.lat.toFixed(6)}","style":"${style}"}&type=search&tk=c8e0b9ae169804fa3d0dbdcc04017804`;

        const route = await this.electronService.invoke('get-tianditu-route', url);

        return route;
    }
   
}
